package com.yupi.yupicturebackend.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.api.imagesearch.ImageSearchApiFacade;
import com.yupi.yupicturebackend.api.imagesearch.model.dto.SearchPictureByPictureRequest;
import com.yupi.yupicturebackend.api.imagesearch.model.vo.ImageSearchResult;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.DeleteRequest;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.RedisConstant;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.picture.*;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.PictureReviewStatusEnums;
import com.yupi.yupicturebackend.model.vo.PictureTagCategoryVo;
import com.yupi.yupicturebackend.model.vo.PictureVo;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/picture")
public class PictureController {
    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private SpaceService spaceService;
    //尝试本地缓存Caffeine
    //创建本地缓存容器，一般可以作为一个config类
    private static final Cache<String, String> LOCAL_CACHE = Caffeine
            .newBuilder()
            .initialCapacity(1024)
            .maximumSize(10_000)
            .expireAfterWrite(Duration.ofMinutes(5))
            .build();

    @PostMapping("/upload")
    public BaseResponse<PictureVo> uploadPicture(@RequestPart MultipartFile multipartFile,
                                                 PictureUploudRequest pictureUploudRequest,
                                                 HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        PictureVo pictureVo = pictureService.uploadPicture(multipartFile, pictureUploudRequest, loginUser);
        return ResultUtils.success(pictureVo);
    }

    @PostMapping("/uploadByBatch")
    public BaseResponse<List<PictureVo>> uploadPictureByBatch(PictureUploudByBatchRequest pictureUploudByBatchRequest,
                                                              HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        List<PictureVo> pictureVoList = pictureService.uploadPictureByBatch(pictureUploudByBatchRequest, loginUser);
        return ResultUtils.success(pictureVoList);
    }

    @PostMapping("/upload/url")
    public BaseResponse<PictureVo> uploadPictureByUrl(@RequestBody PictureUploudRequest pictureUploudRequest,
                                                      HttpServletRequest httpServletRequest) {
        User loginUser = userService.getLoginUser(httpServletRequest);
        String url = pictureUploudRequest.getUrl();
        PictureVo pictureVo = pictureService.uploadPicture(url, pictureUploudRequest, loginUser);
        return ResultUtils.success(pictureVo);
    }

    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest, HttpServletRequest httpServletRequest) {
        boolean result = pictureService.updatePicture(pictureUpdateRequest, httpServletRequest);
        return ResultUtils.success(result, "图片信息更新成功");
    }

    @PostMapping("/update/vo")
    public BaseResponse<Boolean> updatePictureVo(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest httpServletRequest) {
        boolean result = pictureService.updatePictureVo(pictureEditRequest, httpServletRequest);
        return ResultUtils.success(result, "图片信息更新成功");
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        boolean result = pictureService.deletePicture(deleteRequest, request);
        return ResultUtils.success(result, "图片删除成功");
    }

    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(Long id) {
        Picture picture = pictureService.getPictureById(id);
        return ResultUtils.success(picture);
    }

    @GetMapping("/get/vo")
    public BaseResponse<PictureVo> getPictureVoById(Long id,HttpServletRequest request) {
        PictureVo pictureVo = pictureService.getPictureVoById(id);
        Picture picture = PictureVo.VoToObj(pictureVo);
        if (pictureVo.getSpaceId()!= null){
            User user = userService.getLoginUser(request);
            pictureService.checkPictureAuth(picture,user);
        }

        return ResultUtils.success(pictureVo);
    }

    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR, "查询分页条件不能为空");
        Page<Picture> picturePage = new Page<>();
        picturePage.setCurrent(pictureQueryRequest.getCurrent());
        picturePage.setSize(pictureQueryRequest.getPageSize());
        picturePage = pictureService.page(picturePage, pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }
    @Deprecated
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVo>> listPictureVoByPage(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR, "查询分页条件不能为空");
        ThrowUtils.throwIf(pictureQueryRequest.getPageSize() > 20, ErrorCode.PARAMS_ERROR, "分页参数不合法");
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId==null){
            pictureQueryRequest.setNeedSpaceId(true);
        }else {
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            if (space==null){
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            }else {
                if (!loginUser.getId().equals(space.getUserId()) && !userService.isAdmin(loginUser.getId())){
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限查看该空间图片");
                }
            }
        }
        Page<Picture> picturePage = new Page<>(pictureQueryRequest.getCurrent(), pictureQueryRequest.getPageSize());
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnums.PASS.getValue());
        picturePage = pictureService.page(picturePage, pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVo> pictureVoPage = pictureService.getPictureVoPage(picturePage, request);
        return ResultUtils.success(pictureVoPage);
    }


    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVo>> listPictureVoByPageCache(@RequestBody PictureQueryRequest pictureQueryRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureQueryRequest == null, ErrorCode.PARAMS_ERROR, "查询分页条件不能为空");
        ThrowUtils.throwIf(pictureQueryRequest.getPageSize() > 20, ErrorCode.PARAMS_ERROR, "分页参数不合法");
        Page<Picture> picturePage = new Page<>(pictureQueryRequest.getCurrent(), pictureQueryRequest.getPageSize());
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnums.PASS.getValue());
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtil.md5Hex(queryCondition);
        String key = String.format("%s:listPageVoCache:%s", RedisConstant.PICTURE_REDIS_KEY_PREFIX, hashKey);
        String localKey = String.format("listPageVoCache:%s",hashKey);
        //本地缓存的方法实现
        String localCache = LOCAL_CACHE.getIfPresent(key);
        if (localCache != null) {
            Page<PictureVo> pictureVoPage = JSONUtil.toBean(localCache, Page.class);
            return ResultUtils.success(pictureVoPage);
        }
        String redisCache = stringRedisTemplate.opsForValue().get(key);
        if (redisCache != null){
            Page<PictureVo> pictureVoPage = JSONUtil.toBean(redisCache, Page.class);

            LOCAL_CACHE.put(localKey,redisCache);
            return ResultUtils.success(pictureVoPage);
        }
        picturePage = pictureService.page(picturePage, pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVo> pictureVoPage = pictureService.getPictureVoPage(picturePage, request);
        String pictureJson = JSONUtil.toJsonStr(pictureVoPage);
        LOCAL_CACHE.put(localKey,redisCache);
        stringRedisTemplate.opsForValue().set(key, pictureJson, RedisConstant.CACHE_SHORT_TIME, TimeUnit.SECONDS);
        return ResultUtils.success(pictureVoPage);
    }

    @GetMapping("tag_category")
    public BaseResponse<PictureTagCategoryVo> getTagCategory() {
        PictureTagCategoryVo pictureTagCategoryVo = new PictureTagCategoryVo();
        pictureTagCategoryVo.setCategoryList(Arrays.asList("模板", "电商", "表情包", "海报"));
        pictureTagCategoryVo.setTagList(Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意"));
        return ResultUtils.success(pictureTagCategoryVo);
    }

    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> reviewPicture(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR, "审核参数不能为空");
        pictureService.PictureReview(pictureReviewRequest, userService.getLoginUser(request));
        return ResultUtils.success(true, "审核成功");
    }
    /**
     * 以图搜图
     */
    @PostMapping("/search/picture")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getUrl());
        return ResultUtils.success(resultList);
    }
    @PostMapping("/search/color")
    public BaseResponse<List<PictureVo>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        List<PictureVo> result = pictureService.searchPictureByColor(spaceId, picColor, loginUser);
        return ResultUtils.success(result);
    }
   @PostMapping("/edit/batch")
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
       User loginUser = userService.getLoginUser(request);
       return ResultUtils.success(pictureService.PictureEditByBatch(pictureEditByBatchRequest, loginUser));
   }
}
